package metrics

import (
	"fmt"
	"net/http"
	"runtime"
	"sync/atomic"
	"time"
	"xiaoniu-registry/internal/cache"
	"xiaoniu-registry/internal/response"
)

// Metrics 系统指标结构
type Metrics struct {
	// 请求统计
	TotalRequests     int64 `json:"total_requests"`
	HeartbeatRequests int64 `json:"heartbeat_requests"`
	APIRequests       int64 `json:"api_requests"`

	// 服务统计
	TotalServices    int `json:"total_services"`
	TotalInstances   int `json:"total_instances"`
	HealthyInstances int `json:"healthy_instances"`

	// 系统信息
	Uptime      string `json:"uptime"`
	MemoryUsage string `json:"memory_usage"`
	Goroutines  int    `json:"goroutines"`
	GCCount     uint32 `json:"gc_count"`

	// 时间戳
	Timestamp time.Time `json:"timestamp"`
}

// 全局计数器
var (
	totalRequests     int64
	heartbeatRequests int64
	apiRequests       int64
	startTime         = time.Now()
)

// IncrementTotalRequests 增加总请求数
func IncrementTotalRequests() {
	atomic.AddInt64(&totalRequests, 1)
}

// IncrementHeartbeatRequests 增加心跳请求数
func IncrementHeartbeatRequests() {
	atomic.AddInt64(&heartbeatRequests, 1)
}

// IncrementAPIRequests 增加API请求数
func IncrementAPIRequests() {
	atomic.AddInt64(&apiRequests, 1)
}

// GetMetrics 获取当前系统指标
func GetMetrics() *Metrics {
	// 获取内存统计
	var m runtime.MemStats
	runtime.ReadMemStats(&m)

	// 服务统计
	services := cache.QueryServiceList()
	totalServices := len(services)
	totalInstances := 0
	healthyInstances := 0

	for _, service := range services {
		instances := cache.QueryInstancesByServiceName(service.Name)
		totalInstances += len(instances)
		for _, instance := range instances {
			if instance.IsHealth {
				healthyInstances++
			}
		}
	}

	return &Metrics{
		TotalRequests:     atomic.LoadInt64(&totalRequests),
		HeartbeatRequests: atomic.LoadInt64(&heartbeatRequests),
		APIRequests:       atomic.LoadInt64(&apiRequests),
		TotalServices:     totalServices,
		TotalInstances:    totalInstances,
		HealthyInstances:  healthyInstances,
		Uptime:            fmt.Sprintf("%.2f seconds", time.Since(startTime).Seconds()),
		MemoryUsage:       formatBytes(m.Alloc),
		Goroutines:        runtime.NumGoroutine(),
		GCCount:           m.NumGC,
		Timestamp:         time.Now(),
	}
}

// formatBytes 格式化字节数
func formatBytes(bytes uint64) string {
	const unit = 1024
	if bytes < unit {
		return fmt.Sprintf("%d B", bytes)
	}
	div, exp := int64(unit), 0
	for n := bytes / unit; n >= unit; n /= unit {
		div *= unit
		exp++
	}
	return fmt.Sprintf("%.1f %sB", float64(bytes)/float64(div), "KMGTPE"[exp:exp+1])
}

// MetricsHandler 指标API处理器
func MetricsHandler(w http.ResponseWriter, r *http.Request) {
	metrics := GetMetrics()
	response.Success(w, metrics)
}

// StatusHandler 简单状态检查处理器
func StatusHandler(w http.ResponseWriter, r *http.Request) {
	status := map[string]interface{}{
		"status":    "healthy",
		"timestamp": time.Now(),
		"uptime":    time.Since(startTime).String(),
		"version":   "1.0.0",
	}
	response.Success(w, status)
}

// DetailedStatusHandler 详细状态检查处理器
func DetailedStatusHandler(w http.ResponseWriter, r *http.Request) {
	metrics := GetMetrics()

	status := map[string]interface{}{
		"status":    "healthy",
		"timestamp": time.Now(),
		"version":   "1.0.0",
		"metrics":   metrics,
		"components": map[string]string{
			"cache":     "healthy",
			"heartbeat": "healthy",
			"api":       "healthy",
		},
	}

	response.Success(w, status)
}
